<template>
    <view class="custom-form">
        <div style="flex: 1;overflow: auto">
            <form-solution-component :QRCodeForm="QRCodeForm()" v-if="showForm=='solution'" :paramsControl="params"></form-solution-component>
            <!--无需登录时-->
            <rx-layout  v-if="formObject && showForm=='rxForm'">
                <template v-slot:center>
                    <rx-form
                        ref="RxForm"
                        :action="params.action"
                        :formJs="formJs"
                        :resForm="formObject"
                    />
                </template>
                <template v-if="params.action!='detail'" v-slot:footer>
                    <rx-button-list :localButtons="buttons" @change="handMethod"></rx-button-list>
                </template>
            </rx-layout>
        </div>
    </view>
</template>

<script>

/**
 * 二维码表单
 */
import FormApi from "@/api/modules/form/formApi";
import Util from "@/js/Util.js";
import RxLayout from '@/components/RxLayout';
import RxButtonList from "@/components/RxButtonList";
import TokenUtil from "@/common/TokenUtil";
import FormSolutionComponent from '@/views/modules/form/customForm/FormSolutionShow/FormSolutionComponent.vue';
import RxForm from '@/views/modules/form/customForm/RxForm.vue';
import LoginApi from "@/api/login";
import EncryptUtil from "@/assets/encryptUtil";
import Secret from "@/assets/secret";

export default {
    name: "QRCodeForm",
    components: {
        FormSolutionComponent,
        RxForm,
        RxLayout,
        RxButtonList,
    },
    data() {
        return {
            qrcode: "",
            qrCodeAuth: "",
            params:{
                alias: "",
                pkId: "",
                appId: "",
                action:"edit"
            },
            showForm: "",
            //未登录时的表单对象
            formObject:"",
            buttons:[
                {
                    idx_: 1,
                    method: "saveData",
                    type: "submit",
                    mode: "edit",
                    name:this.i18n('commitBtn','提交'),
                    loading:false
                },
            ]
        }
    },
    onLoad(params) {
        this.qrcode = params.qrcode || "";
        this.qrCodeAuth = params.qrCodeAuth || "";
        this.params.alias = params.alias || "";
        this.params.action = params.action ? params.action : "edit";
        if(params.readonly){
            this.params.action = "detail"
        }
        this.params.pkId = params.pkId || "";
        this.params.appId = params.appId || "";
        this.validQrcode();
    },
    methods: {
        i18n(name,text,key){
            return this.$ti18(name,text,"formCustomViewLang",key);
        },
      //获取多语言配置列表
      async getParamsEncrypt(){
        let res = await LoginApi.getParamsEncrypt();
        EncryptUtil.setKeyVal(Secret.key, res.paramsEncrypt || false);
      },
        async validQrcode() {
            await this.getParamsEncrypt();
            FormApi.validQrcode(this.qrcode,this.qrCodeAuth,this.params.alias,this.params.pkId,this.params.appId).then(res => {
                let resData = res?res.data:'';
                let token = TokenUtil.getToken();
                if (!res || !res.success){
                    if(resData && resData.expired){
                        //扫码未在时间段内且二维码还未失效
                        if (resData.time) {
                            //时间段判断
                            uni.reLaunch({
                                url: '/views/modules/form/QRCodeForm/exception/Expires?time=' + resData.time
                            });
                            return;
                        }else {
                            //二维码失效
                            uni.reLaunch({
                                url: '/views/modules/form/QRCodeForm/exception/ErrorQRcode?message=' + res.message
                            });
                            return;
                        }
                    }else {
                        //需要登录
                        if(!token){
                            let pages = getCurrentPages()
                            let currentPage = pages[pages.length - 1]
                            let curRoute = currentPage.route
                            let curParams = currentPage.params
                            currentPage.params['qrcode'] = this.qrcode
                            let fromUrl=curRoute + "?" + this.objectToQueryString(curParams);
                            uni.navigateTo({
                                url: '/pages/RxLogin/Login?fromUrl=' + encodeURIComponent(JSON.stringify(fromUrl))
                            });
                            return;
                        }
                    }
                }
                if(!token){
                    //无需登录时才有formData
                    let scriptJs = Util.replaceDefault(resData.formData.script);
                    this.formJs = new Function('return ' + scriptJs)();
                    this.formObject = resData.formData;
                    //设置标题
                    if(this.formObject && this.formObject.formSolution){
                        uni.setNavigationBarTitle({
                            title: this.formObject.formSolution.name
                        });
                    }
                    this.showForm="rxForm";
                }else {
                    this.showForm="solution";
                }
            });
        },
        /**
         * 将对象字符串
         * name=张三&age=30
         * @param obj
         * @returns {string}
         */
        objectToQueryString(obj) {
            if(!obj){
                return "";
            }
            return Object.keys(obj)
                .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`)
                .join('&');
        },
        //处理按钮
        async handMethod(btn) {
            if (this[btn.method]) {
                this[btn.method](btn);
            }
        },
        // 未登录保存数据
        async saveData(btn) {
            let self_ = this;
            let formData = {};
            let refs = this.$refs;
            btn.loading = true;
            for (let key in refs) {
                if (!key.startWith("RxForm")) {
                    continue;
                }
                //目前单表单
                let vm = refs[key];
                let formVm = (vm instanceof Array) ? vm[0] : vm;
                if (formVm._beforeSubmit) {
                    let rtn = await formVm._beforeSubmit(formVm);
                    if (rtn && !rtn.success) {
                        btn.loading = false;
                        uni.showToast({
                            title: rtn.msg, duration: 1500, icon: 'none'
                        });
                        return;
                    }
                }
                //数据必填，类型校验
                let res = await formVm.formCheckRule(true, true);
                if (!res.success) {
                    btn.loading = false;
                    uni.showToast({
                        title: res.msg, duration: 1500, icon: 'none'
                    });
                    return;
                }
                formData=formVm.data;
            }
            let data = {
                alias: this.params.alias,
                data: formData
            };
            uni.showLoading({
                title: self_.i18n('autosave.saving', '正在保存...')
            });
            FormApi.saveQrcodeForm(data, this.qrcode).then(res => {
                uni.hideLoading();
                if (!res.success) {
                    uni.showToast({
                        title: res.message || self_.$ti18('rxMsa.masWarn.error', '出错了'), duration: 1500, icon: 'none'
                    });
                    return;
                }
                //提交成功
                uni.reLaunch({
                    url: '/views/modules/form/QRCodeForm/exception/Success'
                });
            })
        },
        QRCodeForm(){
            if(this.params.action=="detail"){
                return true
            }
            return  false
        }
    }
}
</script>

<style scoped>

.custom-form {
    height: 100%;
    overflow: hidden;
    display: flex;
    z-index: 1;
    flex-direction: column;
}

.custom-buttons {
    position: relative;
    bottom: 0px;
    overflow: hidden;
    width: 100%;
    padding-bottom: 0.4rem;
    left: 0px;
    background-color: white;
}

.custom-button {
    display: flex;
}

.custom-more-buttons > button {
    background-color: white;
    height: 2rem;
    line-height: 2rem;
    text-align: center;
    border: 1px solid #e8e8e8;
    border-top: none;
}

.custom-button > button {
    flex: 1;
    margin-left: 10px;
    margin-right: 10px;
    text-align: center;
    line-height: 1.5rem;
    background-color: #007AFF;
    border-radius: 5px;
    color: white;
    font-size: .8rem;
    margin-top: .5rem;
}

.custom-button-forbid {
    background-color: #cdd7db !important;
}

</style>
